package custom.security.web.controller;

import com.fasterxml.jackson.annotation.JsonView;
import custom.security.dto.User;
import custom.security.exception.UserParamsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by security on 2017/9/23.
 */
@RestController
public class TestController {


    @GetMapping("/me")
    public Authentication getMeInfo(){
        return SecurityContextHolder.getContext().getAuthentication();
    }


    @GetMapping("/user")
    @JsonView(User.JsonSimple.class)
    public List<User> getUser(){
        List<User> strings = new ArrayList<>();
        strings.add(new User("1","security","wgt110",new Date()));
        strings.add(new User("2","hjh","weriudc",new Date()));
        strings.add(new User("3","fak","debjiv",new Date()));
        return strings;
    }

    @GetMapping("/user/{id}")
    @JsonView(User.JsonDetail.class)
    public User getUserinfo(@PathVariable("id")Integer id){
        System.out.println(id);
        return new User(id.toString(),"security","fdas",new Date());
    }

    @PostMapping("/user")
    public User create(@RequestBody @Validated User user
            , BindingResult bindingResult
                       ){

        if (bindingResult.hasErrors()){
            throw new UserParamsException(bindingResult.getFieldError().getDefaultMessage());
        }

        System.out.println(user);

        user.setId(UUID.randomUUID().toString().replace("-",""));
        return user;

    }

    @PutMapping("/user")
    public User update(@RequestBody @Validated User user,BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            throw new RuntimeException(bindingResult.getFieldError().getDefaultMessage());
        }

        System.out.println(user);
        user.setBirthday(new Date());
        return user;
    }

    @DeleteMapping("/user/{id}")
    public User delete(@PathVariable String id){
        System.out.println(id);
        return new User(id,"ashfjka","fha",new Date());
    }
}
